package com.fengye.proxy.dynamic.cglib;

/**
 * @author gaohaiqing
 * @since 2023/12/12
 */
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CGLIBDynamicProxyExample {
    public static void main(String[] args) {
        // 创建被代理的对象
        RealClass realClass = new RealClass();

        // 创建 MethodInterceptor 实例
        MethodInterceptor interceptor = new MyMethodInterceptor();

        // 使用 Enhancer 类创建代理对象
        RealClass proxyClass = (RealClass) Enhancer.create(
                RealClass.class,
                interceptor
        );

        // 调用代理对象的方法
        proxyClass.method();
    }
}

class RealClass {
    public void method() {
        System.out.println("RealClass: Performing method.");
    }
}

class MyMethodInterceptor implements MethodInterceptor {
    @Override
    public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("Before method invocation.");
        Object result = proxy.invokeSuper(obj, args);
        System.out.println("After method invocation.");
        return result;
    }
}